package com.java110.mall.goods.cmd.product;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.context.Environment;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.file.FileRelDto;
import com.java110.dto.housekeeping.HousekeepingServDto;
import com.java110.dto.housekeeping.HousekeepingTypeDto;
import com.java110.dto.product.ProductDetailDto;
import com.java110.intf.goods.*;
import com.java110.intf.system.IFileInnerServiceSMO;
import com.java110.intf.system.IFileRelInnerServiceSMO;
import com.java110.po.file.FileRelPo;
import com.java110.po.product.ProductPo;
import com.java110.po.product.ProductDetailPo;
import com.java110.po.product.ProductH5MenuPo;
import com.java110.po.product.ProductServKeywordPo;
import com.java110.po.product.ProductSpecValuePo;
import com.java110.po.shop.ShopDistributionModePo;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.utils.util.ListUtil;
import com.java110.utils.util.StringUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;

import java.util.ArrayList;
import java.util.List;

@Java110Cmd(serviceCode = "product.updateProduct")
public class UpdateProductCmd extends Cmd {

    @Autowired
    private IProductInnerServiceSMO productInnerServiceSMOImpl;
    @Autowired
    private IFileRelInnerServiceSMO fileRelInnerServiceSMOImpl;
    @Autowired
    private IFileInnerServiceSMO fileInnerServiceSMOImpl;

    @Autowired
    private IProductSpecValueInnerServiceSMO productSpecValueInnerServiceSMOImpl;

    @Autowired
    private IProductDetailInnerServiceSMO productDetailInnerServiceSMOImpl;

    @Autowired
    private IProductServKeywordInnerServiceSMO productServKeywordInnerServiceSMOImpl;
    @Autowired
    private IShopDistributionModeInnerServiceSMO shopDistributionModeInnerServiceSMOImpl;

    @Autowired
    private IProductH5MenuV1InnerServiceSMO productH5MenuV1InnerServiceSMOImpl;

    @Autowired
    private IHousekeepingTypeInnerServiceSMO housekeepingTypeInnerServiceSMOImpl;


    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {
        Environment.isDevEnv();
        Assert.hasKeyAndValue(reqJson, "prodName", "请求报文中未包含prodName");
        Assert.hasKeyAndValue(reqJson, "keyword", "请求报文中未包含keyword");
        Assert.hasKeyAndValue(reqJson, "categoryId", "请求报文中未包含categoryId");
        Assert.hasKeyAndValue(reqJson, "unitName", "请求报文中未包含unitName");
        Assert.hasKeyAndValue(reqJson, "sort", "请求报文中未包含sort");
        Assert.hasKeyAndValue(reqJson, "isPostage", "请求报文中未包含isPostage");
        Assert.hasKeyAndValue(reqJson, "productId", "productId不能为空");
    }

    @Override
    @Java110Transactional
    public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {
        String storeId = cmdDataFlowContext.getReqHeaders().get("store-id");
        String coverPhoto = reqJson.containsKey("coverPhoto") ? reqJson.getString("coverPhoto") : "";
        JSONArray carouselFigurePhoto = reqJson.containsKey("carouselFigurePhoto") ? reqJson.getJSONArray("carouselFigurePhoto") : null;

        JSONArray productSpecs = reqJson.containsKey("productSpecs") ? reqJson.getJSONArray("productSpecs") : null;

        JSONObject spec = null;
        List<ProductSpecValuePo> productSpecValuePos = null;

        boolean hasDefault = false;
        ProductSpecValuePo productSpecValuePo = null;
        if (productSpecs != null) {
            productSpecValuePos = new ArrayList<>();
            for (int specIndex = 0; specIndex < productSpecs.size(); specIndex++) {
                spec = productSpecs.getJSONObject(specIndex);
                productSpecValuePo = BeanConvertUtil.covertBean(spec, ProductSpecValuePo.class);
                productSpecValuePos.add(productSpecValuePo);
                if ("T".equals(productSpecValuePo.getIsDefault())) {
                    hasDefault = true;
                }
            }
        }

        if (!hasDefault) {
            throw new IllegalArgumentException("请求报文中未包含默认规格");
        }

        ProductPo productPo = BeanConvertUtil.covertBean(reqJson, ProductPo.class);
        productPo.setStoreId(storeId);


        ProductDetailPo productDetailPo = null;
        if (reqJson.containsKey("content")) {
            productDetailPo = new ProductDetailPo();
            productDetailPo.setStoreId(storeId);

            productDetailPo.setContent(reqJson.getString("content"));
        }
        ShopDistributionModePo shopDistributionModePo = BeanConvertUtil.covertBean(reqJson, ShopDistributionModePo.class);

        ResponseEntity<String> responseEntity = update(productPo,
                coverPhoto,
                carouselFigurePhoto,
                productSpecValuePos,
                productDetailPo,
                shopDistributionModePo,
                reqJson);
        cmdDataFlowContext.setResponseEntity(responseEntity);
    }

    public ResponseEntity<String> update(ProductPo productPo, String coverPhoto, JSONArray carouselFigurePhoto,
                                         List<ProductSpecValuePo> productSpecValuePos, ProductDetailPo productDetailPo,
                                         ShopDistributionModePo shopDistributionModePo,
                                         JSONObject reqJson) {
        int flag = 0;
         productInnerServiceSMOImpl.updateProduct(productPo);
//        if (flag < 1) {
//            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "更新失败");
//        }

        doUpdatekeywords(productPo);


        //处理手机菜单
        doH5Menu(reqJson, productPo);

        //保存商品封面
        //删除 图片
        FileRelPo fileRelPo = new FileRelPo();
        fileRelPo.setObjId(productPo.getProductId());
        fileRelPo.setRelTypeCd(FileRelDto.REL_TYPE_CD_GOODS_COVER);
        fileRelInnerServiceSMOImpl.deleteFileRel(fileRelPo);
        doSavaRentingFile(coverPhoto, productPo, FileRelDto.REL_TYPE_CD_GOODS_COVER);

        if (carouselFigurePhoto != null) {
            fileRelPo = new FileRelPo();
            fileRelPo.setObjId(productPo.getProductId());
            fileRelPo.setRelTypeCd(FileRelDto.REL_TYPE_CD_GOODS_CAROUSEL_FIGURE);
            fileRelInnerServiceSMOImpl.deleteFileRel(fileRelPo);
            for (int carouselIndex = 0; carouselIndex < carouselFigurePhoto.size(); carouselIndex++) {
                doSavaRentingFile(carouselFigurePhoto.getString(carouselIndex), productPo, FileRelDto.REL_TYPE_CD_GOODS_CAROUSEL_FIGURE);
            }
        }
        if (productSpecValuePos != null) {
            //删除所有 规格
            ProductSpecValuePo deleteProductSpecValuePo = new ProductSpecValuePo();
            deleteProductSpecValuePo.setStoreId(productPo.getStoreId());
            deleteProductSpecValuePo.setProductId(productPo.getProductId());
            productSpecValueInnerServiceSMOImpl.deleteProductSpecValue(deleteProductSpecValuePo);
            for (ProductSpecValuePo productSpecValuePo : productSpecValuePos) {
                if(StringUtil.isEmpty(productSpecValuePo.getDeduction())){
                    productSpecValuePo.setDeduction("0.00");
                }
                productSpecValuePo.setSpecId("-1");
                productSpecValuePo.setShopId(productPo.getShopId());
                if (StringUtil.isEmpty(productSpecValuePo.getValueId())
                        || productSpecValuePo.getValueId().startsWith("-")) {
                    productSpecValuePo.setStoreId(productPo.getStoreId());
                    productSpecValuePo.setProductId(productPo.getProductId());
                    productSpecValuePo.setValueId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_valueId));
                    flag = productSpecValueInnerServiceSMOImpl.saveProductSpecValue(productSpecValuePo);
                    if (flag < 1) {
                        throw new IllegalArgumentException("保存规格失败");
                    }
                } else {
                    productSpecValueInnerServiceSMOImpl.updateProductSpecValue(productSpecValuePo);
                }
            }
        }

        if (productDetailPo == null) {
            return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");
        }
        ProductDetailDto productDetailDto = new ProductDetailDto();
        productDetailDto.setProductId(productPo.getProductId());
        productDetailDto.setStoreId(productPo.getStoreId());
        List<ProductDetailDto> productDetailDtos = productDetailInnerServiceSMOImpl.queryProductDetails(productDetailDto);

        if (ListUtil.isNull(productDetailDtos)) {
            productDetailPo.setProductId(productPo.getProductId());
            productDetailPo.setShopId(productPo.getShopId());
            productDetailPo.setDetailId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_detailId));
            flag = productDetailInnerServiceSMOImpl.saveProductDetail(productDetailPo);
        } else {
            productDetailPo.setProductId(productPo.getProductId());
            flag = productDetailInnerServiceSMOImpl.updateProductDetail(productDetailPo);

        }
        if (flag < 1) {
            throw new IllegalArgumentException("保存规格失败");
        }


        return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");
    }

    /**
     * 保存房屋租赁 图片
     *
     * @param productPo
     */
    private void doUpdatekeywords(ProductPo productPo) {

        String[] keywor = productPo.getKeyword().replaceAll("；", ";").split(";");

        ProductServKeywordPo servKeyword = new ProductServKeywordPo();
        servKeyword.setObjId(productPo.getProductId());
        servKeyword.setShopId(productPo.getShopId());
        int deunt = productServKeywordInnerServiceSMOImpl.deleteProductServKeyword(servKeyword);
        if (deunt < 1) {
            throw new IllegalArgumentException("关键字删除失败");
        }
        for (String keyword : keywor) {
            ProductServKeywordPo servKeywordPo = new ProductServKeywordPo();
            servKeywordPo.setObjId(productPo.getProductId());
            servKeywordPo.setShopId(productPo.getShopId());
            servKeywordPo.setKeywordId(GenerateCodeFactory.getGeneratorId("13"));
            servKeywordPo.setKeywordName(keyword.trim());
            servKeywordPo.setKeywordType(HousekeepingServDto.KEYWORD_PROD_TYPE_CD);
            int save = productServKeywordInnerServiceSMOImpl.saveProductServKeyword(servKeywordPo);

            if (save < 1) {
                throw new IllegalArgumentException("关键字删除失败");
            }
        }
    }

    /**
     * 保存房屋租赁 图片
     *
     * @param photo
     * @param productPo
     */
    private void doSavaRentingFile(String photo, ProductPo productPo, String fileTypeCd) {

        if (StringUtil.isEmpty(photo)) {
            return;
        }



        FileRelPo fileRelPo = null;
        fileRelPo = new FileRelPo();
        fileRelPo.setObjId(productPo.getProductId());
        fileRelPo.setRelTypeCd(fileTypeCd);
        fileRelPo.setFileRelId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_relId));
        fileRelPo.setFileRealName(photo);
        fileRelPo.setFileSaveName(photo);
        fileRelPo.setSaveWay(FileRelDto.SAVE_WAY_FTP);
        int save = fileRelInnerServiceSMOImpl.saveFileRel(fileRelPo);

        if (save < 1) {
            throw new IllegalArgumentException("保存文件失败");
        }
    }

    private void doH5Menu(JSONObject reqJson, ProductPo productPo) {

        if (!reqJson.containsKey("hktIds")) {
            return;
        }

        JSONArray hktIds = reqJson.getJSONArray("hktIds");

        if (hktIds == null || hktIds.size() < 1) {
            return;
        }

        ProductH5MenuPo productH5MenuPo = new ProductH5MenuPo();
        productH5MenuPo.setProductId(productPo.getProductId());
        productH5MenuV1InnerServiceSMOImpl.deleteProductH5Menu(productH5MenuPo);

        String hktId = "";
        HousekeepingTypeDto housekeepingTypeDto = null;
        List<HousekeepingTypeDto> housekeepingTypeDtos = null;
        for (int hktIndex = 0; hktIndex < hktIds.size(); hktIndex++) {
            hktId = hktIds.getString(hktIndex);
            housekeepingTypeDto = new HousekeepingTypeDto();
            housekeepingTypeDto.setHktId(hktId);
            housekeepingTypeDtos = housekeepingTypeInnerServiceSMOImpl.queryHousekeepingTypes(housekeepingTypeDto);

            if (housekeepingTypeDtos == null || housekeepingTypeDtos.size() < 1) {
                continue;
            }

            productH5MenuPo = new ProductH5MenuPo();
            productH5MenuPo.setHktId(hktId);
            productH5MenuPo.setHktName(housekeepingTypeDtos.get(0).getHktName());
            productH5MenuPo.setProductId(productPo.getProductId());
            productH5MenuPo.setShopId(productPo.getShopId());
            productH5MenuPo.setStoreId(productPo.getStoreId());
            productH5MenuPo.setPhmId(GenerateCodeFactory.getGeneratorId("11"));
            int flag = productH5MenuV1InnerServiceSMOImpl.saveProductH5Menu(productH5MenuPo);

            if (flag < 1) {
                throw new CmdException("保存数据失败");
            }
        }
    }

}
